package com.mccree.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@Controller
@Slf4j
public class MyController {

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","Hello,Shiro");
        return "index";
    }
    @GetMapping("/user/add")
    public String toAdd(){
        return "user/add";
    }
    @RequestMapping("/user/update")
    public String toUpdate(){
        return "user/update";
    }

    @GetMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        @RequestParam(value = "remember",required = false)String remember,
                        Model model){
        //使用shiro，编写认证操作
        //1.获取subject
        Subject subject = SecurityUtils.getSubject();
        System.out.println(subject.getPrincipal());
        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //设置记住我
        remember = remember == null?"false":remember;
        token.setRememberMe(Boolean.parseBoolean(remember));
        //3.执行登录的方法，没有异常就代表登录成功
        try {
            subject.login(token);
            Session session = subject.getSession();
            session.setAttribute("loginUser",username);
            return "index";
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }
    /**
     * 未授权请求
     */
    @RequestMapping("/noAuth")
    @ResponseBody
    public String noAuth(){
        return "警告：擅自访问未授权页面将被CTOS通缉，当前用户已被CTOS监管，相关敏感操作已同步至CTOS数据中心";
    }
    /**
     * 注销
     */
    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "index";
    }
}
